package com.bwie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TbAuthorizedMapper;
import com.bwie.pojo.TbAuthorized;
import com.bwie.pojo.TbSheet;
import com.bwie.service.TbSheetService;
import com.bwie.mapper.TbSheetMapper;
import com.bwie.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

/**
* @author 18229
* @description 针对表【tb_sheet】的数据库操作Service实现
* @createDate 2025-04-17 12:41:10
*/
@Service
public class TbSheetServiceImpl extends ServiceImpl<TbSheetMapper, TbSheet>
    implements TbSheetService{

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //定义一个变量，用于存储redis中的key
    @Autowired
    private TbSheetMapper tbSheetMapper;

    @Autowired
    private TbAuthorizedMapper tbAuthorizedMapper;

    @Override
    public R getSheetList() {
        List<TbSheet> tbSheets = tbSheetMapper.getSheetList(null);
        return R.OK(tbSheets);
    }

    @Override
    public R addSheet(TbSheet tbSheet) {
        //提交数据的时候需要先去缓存当中去进行判断是否存在
        tbSheetMapper.insert(tbSheet);
        List<TbSheet> tbSheets = JSON.parseArray(stringRedisTemplate.opsForValue().get(tbSheetsStr), TbSheet.class);
        for (TbSheet sheet : tbSheets) {
            if (sheet.getName().equals(tbSheet.getName())){
               return R.ERROR(500,"数据已经存在,请勿重复添加");
            }
        }
        return R.OK();
    }

    @Override
    public R getAuthList() {
      List<TbAuthorized> tbAus= tbAuthorizedMapper.getAuthList(null);
      return R.OK(tbAus);

    }

    //将数据缓存到redis中
    //启动程序将数据放入缓存
    //定义一个变量，用于存储redis中的key
    private String tbSheetsStr = "tbSheetsStr";
    @PostConstruct
    public void init(){
        //缓存需要保证缓存的数据不会一直存在，考虑缓存穿透和雪崩效应，每次启动应用程序就会先删除掉缓存
        stringRedisTemplate.delete(tbSheetsStr);
        //设置key值过期时间
        List<TbSheet> tbSheets = tbSheetMapper.getSheetList(null);
        //查询到的列表数据放入缓存
        stringRedisTemplate.opsForValue().set(tbSheetsStr, JSON.toJSONString(tbSheets));
        System.out.println("上报数据已经同步到redis中");












    }
}




